using MediatR;
using Medical.Api.Write.Application.Command.DepartmentManagement.Recycling;
using Medical.Domain.DepartmentInfo;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Medical.Api.Write.Application.Handler.DepartmentManagement.Recycling
{
    public class UpdateRecyclingStatusCommandHandler : IRequestHandler<UpdateRecyclingStatusCommands, ApiResult<int>>
    {
        private readonly IBaseRepository<RecyclingTable> recyclingRep;
        private readonly ILogger<UpdateRecyclingStatusCommandHandler> logger;

        public UpdateRecyclingStatusCommandHandler(
            IBaseRepository<RecyclingTable> recyclingRep, 
            ILogger<UpdateRecyclingStatusCommandHandler> logger)
        {
            this.recyclingRep = recyclingRep;
            this.logger = logger;
        }

        public async Task<ApiResult<int>> Handle(UpdateRecyclingStatusCommands request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation("开始处理回收申请状态更新，ID：{0}，新状态：{1}", request.RecyclingId, request.RecyclingStatus);
                
                // 检查回收申请是否存在
                var existingRecycling = await recyclingRep.GetModelAsync(request.RecyclingId);
                if (existingRecycling == null)
                {
                    logger.LogWarning("未找到ID为{0}的回收申请", request.RecyclingId);
                    return new ApiResult<int>
                    {
                        Code = ApiEnums.NotFound,
                        Data = 0,
                        Msg = $"未找到ID为{request.RecyclingId}的回收申请"
                    };
                }
                
                // 更新回收状态
                existingRecycling.RecyclingStatus = request.RecyclingStatus;
                existingRecycling.UpdateTime = DateTime.Now;
                
                // 更新回收申请
                recyclingRep.Update(existingRecycling);
                
                logger.LogInformation("成功更新回收申请状态，ID：{0}，新状态：{1}", request.RecyclingId, request.RecyclingStatus);
                return new ApiResult<int>
                {
                    Code = ApiEnums.Success,
                    Data = request.RecyclingId,
                    Msg = "成功更新回收申请状态"
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "更新回收申请状态时发生错误：{0}", ex.Message);
                return new ApiResult<int>
                {
                    Code = ApiEnums.Fail,
                    Data = 0,
                    Msg = $"更新回收申请状态失败：{ex.Message}"
                };
            }
        }
    }
} 